package com.example.jiangkt.ergongyi.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.example.jiangkt.ergongyi.R;
import com.example.jiangkt.ergongyi.activity.UserRoomActivity;
import com.example.jiangkt.ergongyi.util.AlertShow;
import com.example.jiangkt.ergongyi.util.CustomAction;
import com.example.jiangkt.ergongyi.util.SocketUtil;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

public class BackstageService extends Service {
    public NetworkReceiver networkReceiver;
    public ServiceReceiver serviceReceiver;
    public SocketUtil socketUtil;
    public String content;
    public String request;
    private MediaPlayer bgPlayer;
    private boolean musicStatus;
    private SoundReceiver soundReceiver;

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        initPlayer();

        networkReceiver = new NetworkReceiver();
        soundReceiver = new SoundReceiver();
        serviceReceiver = new ServiceReceiver();
        this.registerReceiver();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (bgPlayer.isPlaying()) {
            bgPlayer.stop();
        }

        this.unregisterReceiver(networkReceiver);
        this.unregisterReceiver(soundReceiver);
        this.unregisterReceiver(serviceReceiver);
    }

    public void registerReceiver() {
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        this.registerReceiver(networkReceiver, filter);

        IntentFilter filterService = new IntentFilter(CustomAction.SOUND_ACTION);
        this.registerReceiver(soundReceiver, filterService);

        IntentFilter filterSound = new IntentFilter(CustomAction.SERVICE_ACTION);
        this.registerReceiver(serviceReceiver, filterSound);
    }

    private void initPlayer() {
        bgPlayer = MediaPlayer.create(this, R.raw.bg_music);
        if (false) {
            bgPlayer.start();
            bgPlayer.setLooping(true);
        }
    }

    public void initSocket() {
        socketUtil = (SocketUtil) getApplication();
        final CountDownLatch latch = new CountDownLatch(1);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    socketUtil.init();

                }catch (Exception e){

                }finally {
                    latch.countDown();

                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {


                try {
                    latch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                content = null;
                try {
                    //防止空指针socketUtil.getBufferedReader().readLine()
                    //只要服务器返回数据就接收
                    //错误写法：
                    //while (((content = (socketUtil.getBufferedReader()==null?"111":socketUtil.getBufferedReader().readLine())) != null) && (!"111".equals(content))) {

                    //while ((content = (socketUtil.getBufferedReader()==null?"111":socketUtil.getBufferedReader().readLine().toString())) != "111") {
                    //正确写法
//                    while (socketUtil.getBufferedReader()!=null){
                    if (socketUtil.getBufferedReader() != null) {
                        while ((content = socketUtil.getBufferedReader().readLine()) != null) {
                            //"111"代表服务器定时每隔6秒发送消息给客户端，监听客户端是否已经断线
                            if (!"111".equals(content)) {
                                //注册用户时
                                JSONObject jsonObject = JSONObject.parseObject(content);
                                String respType = jsonObject.getString("respType");
                                if ("101".equals(respType) || "102".equals(respType) || "103".equals(respType) || "201".equals(respType) || "202".equals(respType)) {
                                    Intent intent = new Intent(CustomAction.ADD_ACTION);
                                    intent.putExtra("add", respType);
                                    sendBroadcast(intent);
                                    //修改密码时
                                } else if ("401".equals(respType) || "402".equals(respType) || "501".equals(respType) || "502".equals(respType)) {
                                    Intent intent = new Intent(CustomAction.UP_ACTION);
                                    intent.putExtra("up", respType);
                                    sendBroadcast(intent);
                                    //登录时
                                } else if ("301".equals(respType) || "302".equals(respType) || "303".equals(respType) || "305".equals(respType)) {
                                    Intent intent = new Intent(CustomAction.LOGIN_ACTION);
                                    intent.putExtra("login", respType);
                                    if ("305".equals(respType)) {
                                        intent.putExtra("userInfo", jsonObject.getString("userInfo"));
                                    }
                                    sendBroadcast(intent);
                                } else if ("602".equals(respType) || "701".equals(respType) || "802".equals(respType)) {
                                    Intent intent = new Intent(CustomAction.USER_ACTION);
                                    intent.putExtra("getRoom", respType);

                                    if ("701".equals(respType)) {
                                        intent.putExtra("roomList", jsonObject.getString("roomList"));
                                    }
                                    sendBroadcast(intent);
                                } else if ("601".equals(respType) || "801".equals(respType)) {
                                    //直接启动UserRoomActivity
                                    Bundle data = new Bundle();
                                    data.putSerializable("userId",jsonObject.getString("message"));
                                    data.putSerializable("selfSeat", jsonObject.getString("selfSeat"));
                                    Intent startActivity = new Intent(getApplicationContext(), UserRoomActivity.class);
                                    startActivity.putExtras(data);
                                    startActivity(startActivity);
                                    Intent intent = new Intent(CustomAction.USER_ACTION);

                                    //finish主界面activity
                                    intent.putExtra("getRoom", "603");
                                    sendBroadcast(intent);
                                } else if ("901".equals(respType) || "902".equals(respType) || "001".equals(respType) || "002".equals(respType) || "003".equals(respType)
                                        || "004".equals(respType) || "005".equals(respType) || "006".equals(respType) || "007".equals(respType) || "008".equals(respType)
                                        || "009".equals(respType) || "010".equals(respType) || "012".equals(respType) || "013".equals(respType) || "014".equals(respType)) {
                                    Intent intent = new Intent(CustomAction.SEAT_ACTION);
                                    intent.putExtra("getSeat", respType);
                                    if ("901".equals(respType)) {
                                        intent.putExtra("seatList", jsonObject.getString("seatList"));
                                    } else if ("902".equals(respType)) {
                                        intent.putExtra("seat", jsonObject.getString("seat"));
                                    } else if ("002".equals(respType)) {
                                        intent.putExtra("dealCards", jsonObject.getString("dealCards"));
                                    } else if ("003".equals(respType)) {
                                        intent.putExtra("otherSeatNo", jsonObject.getString("message"));
                                        intent.putExtra("dealCards", jsonObject.getString("dealCards"));
                                    } else if ("004".equals(respType)) {
                                        intent.putExtra("otherSeatNo", jsonObject.getString("seatNo"));
                                    } else if ("005".equals(respType)) {
                                        intent.putExtra("pointerSeatNo", jsonObject.getString("pointerSeatNo"));
                                    } else if ("006".equals(respType)) {
                                        intent.putExtra("seatNo", jsonObject.getString("message"));
                                        intent.putExtra("cardList", jsonObject.getString("cardList"));
                                    } else if ("007".equals(respType)) {
                                        intent.putExtra("cardIndex", jsonObject.getString("message"));
                                        intent.putExtra("seatNo", jsonObject.getString("seatNo"));
                                    } else if ("008".equals(respType)) {
                                        intent.putExtra("cardIndex", jsonObject.getString("message"));
                                        intent.putExtra("card", jsonObject.getString("card"));
                                    }else if("010".equals(respType)){
                                        intent.putExtra("seatNo", jsonObject.getString("message"));
                                        intent.putExtra("escrow", jsonObject.getString("escrow"));
                                    }else if("012".equals(respType)){
                                        intent.putExtra("userChip", jsonObject.getString("userChip"));
                                    }else if("013".equals(respType)){
                                        intent.putExtra("bankerChip", jsonObject.getString("bankerChip"));
                                    }else if("014".equals(respType)){
                                        intent.putExtra("seatNo", jsonObject.getString("message"));
                                        intent.putExtra("playerChip", jsonObject.getString("playerChip"));
                                    }
                                    sendBroadcast(intent);

                                } else {
                                    Log.e("respType", content);
                                }
                            } else {
                                /*Date date = new Date();
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                String currentDateTime = sdf.format(date);

                                System.out.println("定时接收服务器请求" + currentDateTime);*/
                            }
                        }
                    } else {
                        if (AlertShow.dialog != null) {
                            AlertShow.dialog.dismiss();
                        }
                    }
                } catch (Exception e) {
                    //只要报错，则不能获取网络
                    if (AlertShow.dialog != null) {
                        AlertShow.dialog.dismiss();
                    }
                    if (socketUtil.getBufferedReader() != null) {
                        try {
                            socketUtil.getBufferedReader().close();
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }
                    }
                    if (socketUtil.getOutputStream() != null) {
                        try {
                            socketUtil.getOutputStream().close();
                        } catch (IOException e2) {
                            e2.printStackTrace();
                        }
                    }
                    if (socketUtil.getSocket() != null) {
                        try {
                            socketUtil.getSocket().close();
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }
                    }
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public class NetworkReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            this.netManager(context);
        }

        /**
         * 读取网络状态，有网络则连接
         *
         * @param context
         */
        public void netManager(Context context) {
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mobNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            NetworkInfo wifiNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

            if (wifiNetInfo.isConnected() || mobNetInfo.isConnected()) {
                Toast.makeText(context, "正在连接二公一...", Toast.LENGTH_SHORT).show();
                initSocket();
            } else {
                if (AlertShow.dialog != null) {
                    AlertShow.dialog.dismiss();
                }
                if (socketUtil != null) {
                    if (socketUtil.getBufferedReader() != null) {
                        try {
                            socketUtil.getBufferedReader().close();
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }
                    }
                    if (socketUtil.getOutputStream() != null) {
                        try {
                            socketUtil.getOutputStream().close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (socketUtil.getSocket() != null) {
                        try {
                            socketUtil.getSocket().close();
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }
                    }
                }
                Toast.makeText(context, "断开二公一", Toast.LENGTH_SHORT).show();
            }
        }
    }

    public class SoundReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            musicStatus = intent.getBooleanExtra("musicStatus", true);

            if (musicStatus) {
                if (bgPlayer.isPlaying()) {
                    bgPlayer.stop();
                } else {
                    bgPlayer = MediaPlayer.create(BackstageService.this, R.raw.bg_music);
                    bgPlayer.start();
                    bgPlayer.setLooping(true);
                }
            } else {
                if (bgPlayer.isPlaying()) {
                    bgPlayer.stop();
                }
            }
        }
    }

    public class ServiceReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            request = intent.getStringExtra("request");

            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        if (socketUtil != null) {
                            //将数据写入网络
                            if (socketUtil.getOutputStream() != null) {
                                socketUtil.getOutputStream().write((request + "\r\n").getBytes("utf-8"));
                            } else {
                                if (AlertShow.dialog != null) {
                                    AlertShow.dialog.dismiss();
                                }
                                initSocket();
                            }
                        } else {
                            if (AlertShow.dialog != null) {
                                AlertShow.dialog.dismiss();
                            }
                            initSocket();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        if (AlertShow.dialog != null) {
                            AlertShow.dialog.dismiss();
                        }
                        initSocket();
                    }
                }
            }).start();
        }
    }
}
